#!groovy

def serverDir,projectName,version,image,buildjob
pipeline {
    agent {
      label "jenkinsNode-21"
    }
    environment {
        gitRepositoryUrl = " http://git.cfhy.work/back/interface-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/accounting-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/statistics-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/support-order-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/config-server.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/user-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/base-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/admin-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/message-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/order-center.git"
        //gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/pay-center.git"
		//gitRepositoryUrl = "https://gitee.com/chengfengkuaiyun/app-gateway.git"
        credentialsId = "0f305fa1-acba-4c0a-9bdf-cdd66f4ea128"
        replicas = 1
        imagePullPolicy = "IfNotPresent" //IfNotPresent
        k8sOpsDir = "/data/jenkins/cfhy-k8s"
        PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
        // SonarQube
        SONAR_PROJECT_PART_URL = "/dashboard?id="
        SONAR_PROJECT_EXCLUSIONS = ""
        SONAR_COVERAGE_EXCLUSIONS = "**/model/**,**/vo/**,**/dto/**,**/entity/**,**/pojo/**,**/controller/**,**/emums/**,**/enums/**,**/annotation/**,**/mapper/**,**/**Application**"


    }
    parameters {
        //gitParameter (name: 'branchAndTag', type: 'PT_BRANCH_TAG', defaultValue: 'master', description: '请选择需要构建的分支或版本')
        choice(name: 'dockerRegistry', choices: ['swr.cn-north-4.myhuaweicloud.com'], description: '请选择docker镜像仓库地址，vpc环境速度较快，但需要环境支撑')
        choice(name: 'dockerRegistryNamespace', choices: ['cfhy-dev'], description: '请选择docker镜像命名空间')
        choice(name: 'k8sNamespace', choices: ['test01'], description: '请选择k8s命名空间')
        choice(name: 'buildJob', choices: ['no','yes'], description: '选择是否关联autotest-Report')
        booleanParam(name: 'injectGrayRelease', defaultValue: true, description: '是否注入灰度发布服务')
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
    }
    tools {
        //maven 'apache-maven-3.6.0'
        maven 'maven'
        jdk 'JDK'
    }

    stages {
        stage('pull code') {
            steps {
                sh "rm -rf ./* .git*"
                script{
                    def changeLogSets = checkout([$class: 'GitSCM',
                                                  branches: [[name: "$GIT_BRANCHES"]],
                                                  doGenerateSubmoduleConfigurations: false,
                                                  extensions: [],
                                                  submoduleCfg: [],
                                                  userRemoteConfigs: [[credentialsId: "${credentialsId}", url: "${gitRepositoryUrl}"]]])
                    version = changeLogSets['GIT_COMMIT']
                }

            }
        }
        stage('more than build') {
            parallel {
        stage('mvn package') {
            steps {
                script{
                    def is_injectGR = true
                    if (params.containsKey('injectGrayRelease')) {
                        is_injectGR = Boolean.valueOf(params.injectGrayRelease)
                    }
                    if (is_injectGR) {
                        println "[INFO] ====> 注入灰度服务"
                        sh """
                            sed -E -e 's/^\\s+<\\/dependencies>/        <dependency>\\n            <groupId>com.cfhy.devops<\\/groupId>\\n            <artifactId>devops-loadbalancer<\\/artifactId>\\n            <version>1.1.0-SNAPSHOT<\\/version>\\n        <\\/dependency>\\n    <\\/dependencies>\\n/g' \
                                  -i.bak \
                                  *-server/pom.xml
                        """
                    }
                }
                sh 'mvn clean package deploy -DskipTests -U -Dmaven.test.skip=true -Pcfhy-test -Dmaven.repo.local=/data/jenkins/.m2/test01/repository'
            }
        }
                stage('Transition Jira') {
                    steps {
                        echo "Transition Jira Start......"
                        catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
                            script {
                                timeout(time: 30, unit: 'SECONDS') {
                                    List changeSets = getCurrentChangeSets()
                                    def gitInfos = []
                                    def gitInfoMapping = [:]
                                    gitInfoMapping.put("repositoryUrl", "${gitRepositoryUrl}")
                                    gitInfoMapping.put("branch", "${GIT_BRANCHES}")
                                    gitInfos.add(gitInfoMapping)
                                    def params = [
                                            namespace  : "test",
                                            jobName    : "${JOB_NAME}",
                                            buildId    : "${BUILD_ID}",
                                            buildNumber: "${BUILD_NUMBER}",
                                            gitInfos   : gitInfos,
                                            changeSets : changeSets
                                    ]
                                    def paramsJson = groovy.json.JsonOutput.toJson(params)
                                    def customHeaders = [
                                            [name: "Authorization-Token", value: "3c9414413c3f86924f85482bf9d0f982605aa209", maskValue: true]
                                    ]
                                    def response = httpRequest(
                                            httpMode: 'POST',
                                            contentType: 'APPLICATION_JSON_UTF8',
                                            responseHandle: 'NONE',
                                            customHeaders: customHeaders,
                                            requestBody: paramsJson,
                                            url: "${JENKINS_JIRA_TRANSITION_URL}"
                                    )
                                }

                            }
                        }
                    }
                }
            }
        }
        // stage('SonarQube Analysis') {
        //     steps {
        //         echo "开始执行 SonarQube 检测 ......"
        //         script {
        //             scannerHome = tool 'SonarQubeScanner'
        //             // projectVersion = sh(script: "mvn help:evaluate -Dmaven.repo.local=/data/jenkins/.m2/dev/repository -Dexpression=project.version -q -DforceStdout", returnStdout: true).trim()
        //             projectVersion = "4.0.0-SNAPSHOT"
        //         }
        //       withSonarQubeEnv('SonarQube') {
        //             sh """
        //                 ${scannerHome}sonar-scanner \
        //                     -Dsonar.projectKey=${env.JOB_NAME} \
        //                     -Dsonar.projectName=${env.JOB_NAME} \
        //                     -Dsonar.sourceEncoding=UTF-8 \
        //                     -Dsonar.language=java \
        //                     -Dsonar.projectVersion=${projectVersion} \
        //                     -Dsonar.java.binaries=**/target/classes \
        //                     -Dsonar.sources=. \
        //                     -Dsonar.exclusions=${env.SONAR_PROJECT_EXCLUSIONS} 
        //             """
        //         }
        //         // 睡眠防止没有分析完成就去请求结果
        //         sleep(120)
        //         timeout(time: 3, unit: 'MINUTES') {
        //             script {
        //                 def qualityGateResponse = waitForQualityGate()
        //                 if (qualityGateResponse.status != 'OK') {
        //                     error "SonarQube 检测不通过: ${qualityGateResponse.status} , 请前往 ${SONAR_HOST_URL}${env.SONAR_PROJECT_PART_URL}${env.JOB_NAME} 查看检测报告"
        //                 } else {
        //                     echo "SonarQube 检测通过, 请前往 ${SONAR_HOST_URL}${env.SONAR_PROJECT_PART_URL}${env.JOB_NAME} 查看检测报告"
        //                 }
        //             }
        //         }
        //     }
        // }
        stage('build image') {
            steps {
                script{
                    def branchTag = "origin/dev"
                    if(branchTag.contains("origin/") || branchTag == null || "" == branchTag || "master" == branchTag || "dev" == branchTag){
                        version = "${BUILD_ID}-" + version.substring(0, 7)
                    } else {
                        version = "${BUILD_ID}-" + branchTag
                    }
                    //def parentProjectName = "${JOB_NAME}".split("/")["${JOB_NAME}".split("/").length - 1]
                    def parentProjectName = "${JOB_NAME}".split("test-")["${JOB_NAME}".split("test-").length - 1]
                    if(parentProjectName.equals("interface-center")){
                        projectName = "interface-server"
                        serverDir = "${WORKSPACE}/$projectName"
                    }else if(!parentProjectName.contains("-server")){
                        projectName = parentProjectName + "-server"
                        serverDir = "${WORKSPACE}/$projectName"
                    }else {
                        projectName = parentProjectName
                        serverDir = "${WORKSPACE}"
                    }
                    println "[INFO] ====> projectName:$projectName"
                    println "[INFO] ====> serverDir:$serverDir"
                    image = """${params.dockerRegistry}/${params.dockerRegistryNamespace}/$projectName:$version"""
                    println "[INFO] ====> image:$image"

                    sh """
                        set +x
                        cd ${serverDir}
                        #echo 'FROM swr.cn-north-4.myhuaweicloud.com/cfhy-common/base-jre:8.212-v1' > Dockerfile
                        # echo 'FROM swr.cn-north-4.myhuaweicloud.com/cfhy-common/base-jre-curl-dev:8.212-v1' > Dockerfile
                        echo 'FROM swr.cn-north-4.myhuaweicloud.com/cfhy-common/base-jre-curl-telnet:8.212' > Dockerfile
                        if [ -f "target/$projectName-sources.jar" ];then
                          rm -rf "target/$projectName-sources.jar"
                        fi
                        docker build -t $image .
                        set -x
                    """
                }
            }
        }
        stage('push image') {
            steps {
                sh "docker push $image && docker rmi $image"
            }
        }
        
        stage('deploy to k8s') {
            steps {
sh """
helm upgrade -i -n${params.k8sNamespace} $projectName ${k8sOpsDir}/helm/environment/test/gaia-chart \
  --set replicaCount=1 \
  --set secret.imageRegistrySecret.name=huaweicloud-registry-secret \
  --set secret.projectEnvSecret.name=project-secret \
  --set image.repository=swr.cn-north-4.myhuaweicloud.com/cfhy-dev/$projectName \
  --set image.tag=$version \
  --set resources.requests.memory=2048Mi \
  --set resources.limits.memory=4096Mi \
  --set resources.requests.cpu=200m \
  --set resources.limits.cpu=4000m
"""
            }
        }
        stage('deploy jacoco') {
            steps {
                script{
                    currentProjectName = "${gitRepositoryUrl}".split("/")["${gitRepositoryUrl}".split("/").length - 1].split(".git")[0]
                    projectPath = "/mnt/cfhy-jacoco/build/cfhy-test/${currentProjectName}"
                    println "[INFO] ====> projectPath:$projectPath"

                }
                sh """
                    #cd order-center-server
                    echo "JOB_NAME=${JOB_NAME}
                    BUILD_ID=${BUILD_ID}
                    GIT_BRANCHES=$GIT_BRANCHES
                    GIT_REPOSITORY_URL=${gitRepositoryUrl}
                    ENVIRONMENT=dev" >> ./project-build-info.properties
                    
                    #tar zcf ${JOB_NAME}-${BUILD_ID}.tar.gz ./* --exclude=**.jar --exclude=**.jar.original 
                    
                    mkdir -p ${projectPath}/${JOB_NAME}-${BUILD_ID}
                    #rsync -a --exclude=*.jar ./ ${projectPath}/${JOB_NAME}-${BUILD_ID}
                    cp -rf ./* ${projectPath}/${JOB_NAME}-${BUILD_ID}
                    #tar -zxf ${projectPath}/${JOB_NAME}-${BUILD_ID}/${JOB_NAME}-${BUILD_ID}.tar.gz -C ${projectPath}/${JOB_NAME}-${BUILD_ID}

                """
            }
        }
        
        stage('buildJob') {
            steps {
                script {
                    if ( "${params.buildJob}" == 'yes' ) {
                        // 延迟构建下游任务'autotest-Report'并传参，静默等待230秒，跳过等待直接执行下一个stage
                        buildjob = build job :'autotest-Report', quietPeriod: 230, wait:false, 
                                   parameters:[string(name: "projectName" , value: "interface-center"), 
                                               string(name: "branchName" , value: "$GIT_BRANCHES"),
                                               string(name: "podName" , value: "$projectName")]
                    }
                }
            }
        }
        
        stage('health check') {
            steps {
                echo " TO DO !"
            }
        }
    }
    post {
        failure {
            wrap([$class: 'BuildUser']) {
                script {
                    BUILD_USER_ID = "${env.BUILD_USER_ID}"
                    BUILD_USER = "${env.BUILD_USER}"
                    BUILD_USER_EMAIL = "${env.BUILD_USER_EMAIL}"
                    BUILD_USER_MOBILE = "${env.BUILD_USER_MOBILE}"
                }

                dingtalk (
                    robot: "12b8fa76-8236-473a-95f8-a1d45367050a",
                    type:'ACTION_CARD',
                    atAll: false,
                    title: "构建失败：${env.JOB_NAME}",
                    messageUrl: 'xxxx',
                    text: [
                        "### [${env.JOB_NAME}](${env.JOB_URL}) ",
                        '---',
                        "- **任务**：[${currentBuild.displayName}](${env.BUILD_URL})",
                        '- **状态**：<font color=#EE0000 >失败</font>',
                        "- **持续时间**：${currentBuild.durationString}".split("and counting")[0],
                        "- **代码分支**：${env.GIT_BRANCHES}",
                        "- **执行人**：${BUILD_USER}",
                        "- **构建日志**：${env.BUILD_URL}/console",
                        "- **sonar检测不通过**：@李磊${SONAR_HOST_URL}${env.SONAR_PROJECT_PART_URL}${env.JOB_NAME}",
                    ]
                )
            }
        }
        success {
            wrap([$class: 'BuildUser']) {
                script {
                    BUILD_USER_ID = "${env.BUILD_USER_ID}"
                    BUILD_USER = "${env.BUILD_USER}"
                    BUILD_USER_EMAIL = "${env.BUILD_USER_EMAIL}"
                    BUILD_USER_MOBILE = "${env.BUILD_USER_MOBILE}"
                }
                dingtalk (
                    robot: "12b8fa76-8236-473a-95f8-a1d45367050a",
                    type:'ACTION_CARD',
                    atAll: false,
                    title: "构建成功：${env.JOB_NAME}",
                    messageUrl: 'xxxx',
                    text: [
                        "### [${env.JOB_NAME}](${env.JOB_URL}) ",
                        '---',
                        "- **任务**：[${currentBuild.displayName}](${env.BUILD_URL})",
                        '- **状态**：<font color=#24D438 >成功</font>',
                        "- **持续时间**：${currentBuild.durationString}".split("and counting")[0],
                        "- **代码分支**：${env.GIT_BRANCHES}",
                        "- **执行人**：${BUILD_USER}",
                        "- **构建日志**：${env.BUILD_URL}/console",
                        "- **sonar检测通过**：${SONAR_HOST_URL}${env.SONAR_PROJECT_PART_URL}${env.JOB_NAME}",
                    ]
                )
            }
        }
        aborted {
            wrap([$class: 'BuildUser']) {
                script {
                    BUILD_USER_ID = "${env.BUILD_USER_ID}"
                    BUILD_USER = "${BUILD_USER}"
                    BUILD_USER_EMAIL = "${env.BUILD_USER_EMAIL}"
                    BUILD_USER_MOBILE = "${env.BUILD_USER_MOBILE}"
                }
                dingtalk (
                    robot: "12b8fa76-8236-473a-95f8-a1d45367050a",
                    type:'ACTION_CARD',
                    atAll: false,
                    title: "终止构建：${env.JOB_NAME}",
                    messageUrl: 'xxxx',
                    text: [
                        "### [${env.JOB_NAME}](${env.JOB_URL}) ",
                        '---',
                        "- **任务**：[${currentBuild.displayName}](${env.BUILD_URL})",
                        '- **状态**：<font color=#EE0000 >终止</font>',
                        "- **持续时间**：${currentBuild.durationString}".split("and counting")[0],
                        "- **代码分支**：${env.GIT_BRANCHES}",
                        "- **执行人**：${BUILD_USER}",
                        "- **构建日志**：${env.BUILD_URL}/console",
                    ]
                )
            }
        }
    }
}
@NonCPS
List getCurrentChangeSets() {
    def currentChangeSets = []
    for (changeLogSet in currentBuild.changeSets) {
        for (entry in changeLogSet.getItems()) {
            def map = [:]
            map.put("commitId", entry.commitId)
            map.put("msg", entry.msg)
            map.put("comment", entry.comment)
            map.put("authorEmail", entry.authorEmail)
            map.put("authorFullName", entry.author.fullName)
            map.put("authorAbsoluteUrl", entry.author.absoluteUrl)
            map.put("timestamp", entry.timestamp)
            currentChangeSets.add(map)
        }
    }
    return currentChangeSets
}